<template>
  <div class="auto-bid-config">
    <el-dialog 
      v-model="visible" 
      title="自动出价配置" 
      width="900px"
      :close-on-click-modal="false"
      @close="handleClose"
    >
      <div v-if="member" class="member-info">
        <div class="member-card">
          <div class="member-avatar">
            <el-avatar :src="getCustomerAvatar(member.id)" :size="48">
              {{ getCustomerInitials(member.nickname) }}
            </el-avatar>
          </div>
          <div class="member-details">
            <div class="member-name">{{ member.nickname || '未知用户' }}</div>
            <div class="member-id">ID: {{ member.id }}</div>
            <div class="member-phone">{{ member.phone || '15988373296' }}</div>
            <div class="member-level">
              <el-tag :type="getLevelTagType(member.level)" size="small">
                {{ member.level || 'L1' }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>

      <el-form :model="form" label-width="140px" class="config-form">
        <!-- 基础配置 -->
        <el-divider content-position="left">
          <el-icon><Setting /></el-icon>
          基础配置
        </el-divider>
        
        <el-form-item label="启用状态">
          <el-switch 
            v-model="form.enabled" 
            @change="handleEnableChange"
          />
        </el-form-item>

                <!-- 账号配置 -->
        <el-divider content-position="left">
          <el-icon><User /></el-icon>
          账号配置
        </el-divider>

        <el-form-item label="执行账号">
          <div class="account-controls">
            <el-button 
              type="primary" 
              size="small" 
              @click="addAccount"
              :disabled="form.accounts.length >= 10 || !form.enabled"
            >
              <el-icon><Plus /></el-icon>
              添加账号 ({{ form.accounts.length }}/10)
            </el-button>
            <el-button 
              type="info" 
              size="small" 
              @click="sortAccounts"
              :disabled="form.accounts.length <= 1 || !form.enabled"
            >
              <el-icon><Sort /></el-icon>
              排序
            </el-button>
          </div>
        </el-form-item>

        <div class="accounts-scroll-container">
          <div class="accounts-container">
            <div 
              v-for="(account, index) in form.accounts" 
              :key="index" 
              class="account-card"
              :class="{ disabled: !form.enabled }"
            >
              <div class="account-header">
                <div class="account-order">
                  <el-tag type="primary" size="small">执行顺序 {{ account.order }}</el-tag>
                </div>
                <div class="account-actions">
                  <el-button 
                    v-if="form.accounts.length > 1"
                    type="danger" 
                    size="small" 
                    @click="removeAccount(index)"
                    :disabled="!form.enabled"
                  >
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </div>
              </div>

              <el-row :gutter="16">
                <el-col :span="16">
                  <el-form-item label="交易账号" required>
                    <el-select 
                      v-model="account.accountId" 
                      placeholder="请选择交易账号"
                      style="width: 100%"
                      :disabled="!form.enabled"
                      @change="(value) => selectTradeAccount(index, value)"
                      filterable
                    >
                      <el-option 
                        v-for="tradeAccount in availableTradeAccounts" 
                        :key="tradeAccount.id" 
                        :label="`${tradeAccount.accountNickname} (${tradeAccount.account})`" 
                        :value="tradeAccount.id"
                      >
                        <div class="account-option">
                          <div class="account-name">{{ tradeAccount.accountNickname }}</div>
                          <div class="account-detail">{{ tradeAccount.account }} | {{ tradeAccount.site }}</div>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="使用次数" required>
                    <el-input-number 
                      v-model="account.times" 
                      :min="1" 
                      :max="100"
                      controls-position="right"
                      style="width: 100%"
                      :disabled="!form.enabled"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <div class="account-info" v-if="account.accountId">
                <div class="info-item">
                  <span class="label">账号ID:</span>
                  <span class="value">{{ account.accountId }}</span>
                </div>
                <div class="info-item">
                  <span class="label">昵称:</span>
                  <span class="value">{{ account.accountNickname }}</span>
                </div>
                <div class="info-item">
                  <span class="label">账号:</span>
                  <span class="value">{{ account.account }}</span>
                </div>
                <div class="info-item">
                  <span class="label">手机:</span>
                  <span class="value">{{ account.phone }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>


      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="saveConfig" :loading="saving">
            保存配置
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 排序弹窗 -->
    <el-dialog v-model="sortDialogVisible" title="账号排序" width="500px">
      <div class="sort-container">
        <div 
          v-for="(account, index) in form.accounts" 
          :key="index"
          class="sort-item"
          draggable="true"
          @dragstart="handleDragStart(index)"
          @dragover.prevent
          @drop="handleDrop(index)"
        >
          <el-icon class="drag-handle"><Rank /></el-icon>
          <span class="sort-text">{{ account.accountNickname || '未选择账号' }}</span>
          <span class="sort-order">顺序 {{ account.order }}</span>
        </div>
      </div>
      <template #footer>
        <el-button @click="sortDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSort">确认排序</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Setting, 
  User, 
  Plus, 
  Delete, 
  Sort, 
  Rank
} from '@element-plus/icons-vue'

interface Member {
  id: string
  nickname?: string
  phone?: string
  level?: string
}

interface TradeAccount {
  id: string
  site: string
  account: string
  accountNickname: string
  phone: string
  status: string
}

interface AccountConfig {
  order: number
  accountId: string
  accountNickname: string
  account: string
  phone: string
  times: number
}

interface AutoBidForm {
  enabled: boolean
  accounts: AccountConfig[]
}

const props = defineProps<{
  modelValue: boolean
  member: Member | null
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'save': [config: any]
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const saving = ref(false)
const sortDialogVisible = ref(false)
const draggedIndex = ref(-1)

// 表单数据
const form = reactive<AutoBidForm>({
  enabled: false,
  accounts: []
})

// 交易账号数据
const tradeAccounts = ref<TradeAccount[]>([])

const availableTradeAccounts = computed(() => {
  return tradeAccounts.value.filter(account => account.status === '启用')
})

// 监听弹窗打开，加载数据
watch(visible, (newVal) => {
  if (newVal && props.member) {
    loadTradeAccounts()
    loadAutoBidConfig(props.member.id)
  }
})

function loadTradeAccounts() {
  // 模拟从API获取交易账号数据
  tradeAccounts.value = [
    {
      id: 'TA001',
      site: 'yahoo_auction',
      account: 'yahoo_user1',
      accountNickname: '雅虎拍卖账号1',
      phone: '13800138001',
      status: '启用'
    },
    {
      id: 'TA002',
      site: 'mercari',
      account: 'mercari_user2',
      accountNickname: '煤炉账号2',
      phone: '13800138002',
      status: '启用'
    },
    {
      id: 'TA003',
      site: 'yahoo_flea',
      account: 'yahoo_flea_user',
      accountNickname: '雅虎闲置账号',
      phone: '13800138003',
      status: '启用'
    },
    {
      id: 'TA004',
      site: 'rakuten',
      account: 'rakuten_user1',
      accountNickname: '乐天账号1',
      phone: '13800138004',
      status: '启用'
    },
    {
      id: 'TA005',
      site: 'amazon',
      account: 'amazon_user1',
      accountNickname: '亚马逊账号1',
      phone: '13800138005',
      status: '启用'
    }
  ]
}

function loadAutoBidConfig(memberId: string) {
  // 从localStorage加载配置，实际应该从API获取
  const savedConfig = localStorage.getItem(`autoBidConfig_${memberId}`)
  if (savedConfig) {
    const config = JSON.parse(savedConfig)
    // 只保留需要的字段
    form.enabled = config.enabled || false
    form.accounts = config.accounts || []
  } else {
    // 默认配置
    resetForm()
  }
}

function resetForm() {
  Object.assign(form, {
    enabled: false,
    accounts: [
      {
        order: 1,
        accountId: '',
        accountNickname: '',
        account: '',
        phone: '',
        times: 1
      }
    ]
  })
}

function handleEnableChange(enabled: boolean) {
  // 简单的开关切换，无需确认
}

function addAccount() {
  if (form.accounts.length >= 10) {
    ElMessage.warning('最多只能配置10个账号')
    return
  }
  
  const newOrder = form.accounts.length + 1
  form.accounts.push({
    order: newOrder,
    accountId: '',
    accountNickname: '',
    account: '',
    phone: '',
    times: 1
  })
}

function selectTradeAccount(accountIndex: number, accountId: string) {
  const account = form.accounts[accountIndex]
  const tradeAccount = availableTradeAccounts.value.find(acc => acc.id === accountId)
  
  if (tradeAccount) {
    account.accountId = tradeAccount.id
    account.accountNickname = tradeAccount.accountNickname
    account.account = tradeAccount.account
    account.phone = tradeAccount.phone
  }
}

function removeAccount(index: number) {
  ElMessageBox.confirm(
    '确定要删除这个账号配置吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    form.accounts.splice(index, 1)
    // 重新排序
    form.accounts.forEach((account, idx) => {
      account.order = idx + 1
    })
    ElMessage.success('账号配置已删除')
  })
}

function sortAccounts() {
  sortDialogVisible.value = true
}

function handleDragStart(index: number) {
  draggedIndex.value = index
}

function handleDrop(index: number) {
  if (draggedIndex.value === -1) return
  
  const accounts = [...form.accounts]
  const draggedAccount = accounts[draggedIndex.value]
  accounts.splice(draggedIndex.value, 1)
  accounts.splice(index, 0, draggedAccount)
  
  // 更新顺序
  accounts.forEach((account, idx) => {
    account.order = idx + 1
  })
  
  form.accounts = accounts
  draggedIndex.value = -1
}

function confirmSort() {
  sortDialogVisible.value = false
  ElMessage.success('账号顺序已更新')
}

function validateForm(): boolean {
  if (!form.enabled) {
    return true
  }
  
  // 验证账号配置
  for (const account of form.accounts) {
    if (!account.accountId) {
      ElMessage.warning('请选择交易账号')
      return false
    }
    if (account.times <= 0) {
      ElMessage.warning('次数必须大于0')
      return false
    }
  }
  
  // 验证自定义策略
  if (form.strategy === 'custom' && (form.customBidRate < 1 || form.customBidRate > 200)) {
    ElMessage.warning('自定义出价比例必须在1-200%之间')
    return false
  }
  
  return true
}

async function saveConfig() {
  if (!validateForm()) return
  
  saving.value = true
  
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    if (props.member) {
      // 保存到localStorage，实际应该保存到API
      localStorage.setItem(`autoBidConfig_${props.member.id}`, JSON.stringify(form))
    }
    
    ElMessage.success('自动出价配置保存成功')
    emit('save', form)
    visible.value = false
  } catch (error) {
    ElMessage.error('保存失败，请重试')
  } finally {
    saving.value = false
  }
}

function handleClose() {
  visible.value = false
}

function getCustomerAvatar(customerId: string) {
  return `https://api.dicebear.com/7.x/avataaars/svg?seed=${customerId}`
}

function getCustomerInitials(nickname: string) {
  if (!nickname) return 'U'
  return nickname.substring(0, 2).toUpperCase()
}

function getLevelTagType(level: string) {
  const levelMap: Record<string, string> = {
    'L1': 'info',
    'L2': 'success',
    'L3': 'warning',
    'L4': 'danger',
    'L5': 'danger',
    'L6': 'danger',
    'L7': 'danger'
  }
  return levelMap[level] || 'info'
}
</script>

<style scoped>
.auto-bid-config {
  .member-info {
    margin-bottom: 24px;
  }
  
  .member-card {
    display: flex;
    align-items: center;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 8px;
    gap: 16px;
  }
  
  .member-details {
    flex: 1;
  }
  
  .member-name {
    font-size: 16px;
    font-weight: 600;
    color: #303133;
    margin-bottom: 4px;
  }
  
  .member-id {
    font-size: 12px;
    color: #909399;
    margin-bottom: 2px;
  }
  
  .member-phone {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }
  
  .config-form {
    margin-top: 24px;
  }
  
  .form-tip {
    margin-top: 8px;
    font-size: 12px;
    color: #909399;
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .unit-text {
    margin-left: 8px;
    color: #909399;
    font-size: 12px;
  }
  
  .account-controls {
    display: flex;
    gap: 12px;
    margin-bottom: 16px;
  }
  
  .accounts-scroll-container {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    padding: 16px;
    background: #fafafa;
    margin-bottom: 24px;
    
    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3px;
      
      &:hover {
        background: #a8a8a8;
      }
    }
  }
  
  .accounts-container {
    margin-bottom: 0;
  }
  
  .account-card {
    margin-bottom: 16px;
    padding: 16px;
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    background: #fff;
    transition: all 0.3s;
    
    &.disabled {
      opacity: 0.6;
      pointer-events: none;
    }
    
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
    }
  }
  
  .account-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  
  .account-info {
    margin-top: 12px;
    padding: 12px;
    background: #f5f7fa;
    border-radius: 4px;
    display: flex;
    flex-wrap: wrap;
    gap: 16px;
  }
  
  .info-item {
    display: flex;
    align-items: center;
    gap: 4px;
  }
  
  .info-item .label {
    font-size: 12px;
    color: #909399;
  }
  
  .info-item .value {
    font-size: 12px;
    color: #303133;
    font-weight: 500;
  }
  
  .account-option {
    display: flex;
    flex-direction: column;
    gap: 2px;
  }
  
  .account-name {
    font-size: 14px;
    color: #303133;
  }
  
  .account-detail {
    font-size: 12px;
    color: #909399;
  }
  
  .dialog-footer {
    text-align: center;
    width: 100%;
  }
  
  .sort-container {
    max-height: 400px;
    overflow-y: auto;
  }
  
  .sort-item {
    display: flex;
    align-items: center;
    padding: 12px;
    margin-bottom: 8px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background: #fff;
    cursor: move;
    transition: all 0.3s;
    
    &:hover {
      border-color: #409eff;
      background: #f0f9ff;
    }
  }
  
  .drag-handle {
    margin-right: 8px;
    color: #909399;
  }
  
  .sort-text {
    flex: 1;
    font-size: 14px;
    color: #303133;
  }
  
  .sort-order {
    font-size: 12px;
    color: #909399;
  }
}
</style> 